﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Event_Planner;
 
namespace Event_Planner
{
    public partial class Shop_Apppication : Form
    {
        DB db;
        int selectedShopId, userId = 0;
        double totalAmount = 0;
        List<Shop> shopList;

        public Shop_Apppication()
        {
            InitializeComponent();

            db = new DB();
            shopList = getAllShops();//new List<Shop>();

            this.cbShops.Items.Add("Select a shop");   //add the first items of the combo boxes
            this.cbShops2.Items.Add("Select a shop");
            this.cbShops.SelectedIndex = 0;            //make it the default selected item
            this.cbShops2.SelectedIndex = 0;
            //List<Shop> shops = getAllShops();          //get all the shops
            foreach (Shop shop in shopList)               //go through the list of shops and add their names to the combo box
            {
                this.cbShops.Items.Add(shop.Name);
                this.cbShops2.Items.Add(shop.Name);
            }
        }

        public List<Shop> getAllShops()
        {
            List<Shop> shops = new List<Shop>();
            //1. get all shops
            DataTable shopRecords = db.getAllShopsFromDB();
            int shopId;
            string shopName;
            for (int i = 0; i < shopRecords.Rows.Count; i++)
            {
                shopId = Convert.ToInt32(shopRecords.Rows[i]["shop_id"].ToString());
                shopName = shopRecords.Rows[i]["name"].ToString();
                Shop shop = new Shop(shopId, shopName);
                //2. get items for each shop
                shop.Items = getShopItems(shop.Id);
                shops.Add(shop);
            }
            return shops;
        }

        public List<Item> getShopItems(int shopId)
        {
            List<Item> items = new List<Item>();
            DataTable itemRecords = db.getShopItemsFromDB(shopId);
            int itemId;
            string itemName;
            double itemPrice;
            for (int i = 0; i < itemRecords.Rows.Count; i++)
            {
                itemId = Convert.ToInt32(itemRecords.Rows[i]["item_id"].ToString());
                itemName = itemRecords.Rows[i]["name"].ToString();
                itemPrice = Convert.ToDouble(itemRecords.Rows[i]["price"].ToString());
                items.Add(new Item(itemId, itemName, itemPrice));
            }
            return items;
        }

        public List<Item> getAllItems()
        {
            List<Item> items = new List<Item>();
            DataTable itemRecords = db.getAllItemsFromDB();
            int itemId;
            string itemName;
            double itemPrice;
            for (int i = 0; i < itemRecords.Rows.Count; i++)
            {
                itemId = Convert.ToInt32(itemRecords.Rows[i]["item_id"].ToString());
                itemName = itemRecords.Rows[i]["name"].ToString();
                itemPrice = Convert.ToDouble(itemRecords.Rows[i]["price"].ToString());
                items.Add(new Item(itemId, itemName, itemPrice));
            }
            return items;
        }

        public bool itemIsAlreadyAdded(string shopName, string itemName)
        {
            for (int i = 0; i < this.dataGridView1.Rows.Count - 1; i++)
            {
                //get the selected row
                DataGridViewRow selectedRow = dataGridView1.Rows[i];
                //get the selected item and shop
                string selectedItemName = selectedRow.Cells[0].Value.ToString();
                string selectedShopName = selectedRow.Cells[4].Value.ToString();
                if (selectedItemName == itemName && selectedShopName == shopName)
                {
                    return true;
                }
            }
            return false;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
           
            //this.cbShops.Items.Add("Select a shop");   //add the first items of the combo boxes
            //this.cbShops2.Items.Add("Select a shop");
            //this.cbShops.SelectedIndex = 0;            //make it the default selected item
            //this.cbShops2.SelectedIndex = 0;
            ////List<Shop> shops = getAllShops();          //get all the shops
            //foreach (Shop shop in shopList)               //go through the list of shops and add their names to the combo box
            //{
            //    this.cbShops.Items.Add(shop.Name);
            //    this.cbShops2.Items.Add(shop.Name);
            //}
        }

        public int getShopId(string shopName)
        {
            for (int i = 0; i < shopList.Count; i++)
            {
                if (shopList[i].Name == shopName)
                {
                    return shopList[i].Id;
                }
            }
            return 0;
        }

        public Item getItem(int shopId, string itemName)
        {
            for (int i = 0; i < shopList.Count; i++)
            {
                if (shopList[i].Id == shopId)
                {
                    for (int j = 0; j < shopList[i].Items.Count; j++)
                    {
                        if (shopList[i].Items[j].Name == itemName)
                        {
                            return shopList[i].Items[j];
                        }
                    }
                }
            }
            return null;
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (this.txtQuantity.Text == "")
            {
                MessageBox.Show("Enter a quantity");
            }
            else
            {
                int quantity = Convert.ToInt32(this.txtQuantity.Text);
                if (quantity > 0)
                {
                    string selectedShopName = this.cbShops.SelectedItem.ToString();
                    string selectedItemName = this.cbItems.SelectedItem.ToString();
                    Item selectedItem = getItem(selectedShopId, selectedItemName);
                    double total = quantity * selectedItem.Price;
                    totalAmount += total;
                    if (!this.itemIsAlreadyAdded(selectedShopName, selectedItem.Name))
                    {
                        int user_Id = getUserId();
                        double balance = db.getUserBalance(user_Id);
                        if (balance >= totalAmount)
                        {
                            this.dataGridView1.Rows.Add(selectedItem.Name, quantity, selectedItem.Price, total, selectedShopName);
                            this.labelTotal.Text = totalAmount.ToString();
                        }
                        else
                        {
                            totalAmount -= total;
                            MessageBox.Show("Insufficient Balance, the item cannot be added!");
                        }
                    }
                    else
                    {
                        MessageBox.Show("The item is already added");
                    }
                }
                else
                {
                    MessageBox.Show("Enter a valid quantity");
                }
            }
        }

        private void cbShops_SelectedIndexChanged(object sender, EventArgs e)
        {
            string selectedShopName = this.cbShops.SelectedItem.ToString();
            if (selectedShopName != "Select a shop")
            {
                selectedShopId = getShopId(selectedShopName);
                if (selectedShopId != 0)
                {
                    this.cbItems.Items.Clear();
                    List<Item> items = getShopItems(selectedShopId); //get all the items
                    foreach (Item item in items) //go through the list of items and add their names to the combo box
                    {
                        this.cbItems.Items.Add(item.Name);
                    }
                    this.cbItems.SelectedIndex = 0;
                }
            }

        }

        private void btnRemove_Click(object sender, EventArgs e)
        {
            if (this.dataGridView1.Rows[0].Cells[0].Value != null)
            {
                for (int i = 0; i < this.dataGridView1.SelectedRows.Count; i++)
                {
                    int selectedRowIndex = this.dataGridView1.SelectedCells[i].RowIndex;
                    DataGridViewRow selectedRow = dataGridView1.Rows[selectedRowIndex];
                    double selectedTotal = Convert.ToDouble(selectedRow.Cells[3].Value);
                    totalAmount -= selectedTotal;
                    this.dataGridView1.Rows.RemoveAt(selectedRowIndex);
                }
                this.labelTotal.Text = totalAmount.ToString();
            }
            else
            {
                MessageBox.Show("You cannot remove an inexisting item!");
            }
        }

        private void btnBuy_Click(object sender, EventArgs e)
        {
            if (this.txtUserId.Text == "")
            {
                MessageBox.Show("Enter the user's Id");
            }
            else
            {
                int user_Id = Convert.ToInt32(this.txtUserId.Text);
                if (user_Id > 0)
                {
                    double balance = db.getUserBalance(user_Id);
                    if (balance >= totalAmount)
                    {
                        //check if the dataGridView is empty
                        if (this.dataGridView1.Rows[0].Cells[0].Value != null)
                        {
                            for (int i = 0; i < this.dataGridView1.Rows.Count - 1; i++)
                            {
                                //get the selected row
                                DataGridViewRow selectedRow = dataGridView1.Rows[i];
                                //get the selected data
                                string selectedItemName = selectedRow.Cells[0].Value.ToString();
                                int selectedQuantity = Convert.ToInt32(selectedRow.Cells[1].Value);
                                double selectedPrice = Convert.ToDouble(selectedRow.Cells[2].Value);
                                double selectedTotal = Convert.ToDouble(selectedRow.Cells[3].Value);
                                string selectedShopName = selectedRow.Cells[4].Value.ToString();
                                int shopId = this.getShopId(selectedShopName);
                                int itemId = this.getItem(shopId, selectedItemName).Id;
                                db.insertParticipantItem(user_Id, itemId, selectedQuantity);
                            }
                            int accountNumber = db.getUserAccountNumber(user_Id);
                            db.withdrawParticipantAccount(accountNumber, totalAmount);
                            MessageBox.Show("The items were successfully bought");
                        }
                        else
                        {
                            MessageBox.Show("You need to add some items first");
                        }
                    }
                    else
                    {
                        MessageBox.Show("The user's account balance is not enough for this purchase");
                    }
                }
                else
                {
                    MessageBox.Show("Enter a valid user Id");
                }
            }
        }

        private void btnIncrease_Click(object sender, EventArgs e)
        {
            if (this.dataGridView1.Rows[0].Cells[0].Value != null)
            {
                for (int i = 0; i < this.dataGridView1.SelectedRows.Count; i++)
                {
                    //get the index of the selected row
                    int selectedRowIndex = this.dataGridView1.SelectedCells[i].RowIndex;
                    //get the selected row
                    DataGridViewRow selectedRow = dataGridView1.Rows[selectedRowIndex];
                    //get the selected quantity, price and total
                    double selectedQuantity = Convert.ToInt32(selectedRow.Cells[1].Value);
                    double selectedPrice = Convert.ToDouble(selectedRow.Cells[2].Value);
                    double selectedTotal = Convert.ToDouble(selectedRow.Cells[3].Value);
                    //set the new quantity and total
                    selectedRow.Cells[1].Value = ++selectedQuantity;
                    selectedRow.Cells[3].Value = selectedPrice * selectedQuantity;
                    //subtract the old total from the totalAmount
                    totalAmount -= selectedTotal;
                    //add the new total to the total amount
                    totalAmount += selectedPrice * selectedQuantity;
                }
                this.labelTotal.Text = totalAmount.ToString();
            }
            else
            {
                MessageBox.Show("You cannot increase an inexisting quantity!");
            }
        }

        private void btnDecrease_Click(object sender, EventArgs e)
        {
            //check if the dataGridView is empty
            if (this.dataGridView1.Rows[0].Cells[0].Value != null)
            {
                for (int i = 0; i < this.dataGridView1.SelectedRows.Count; i++)
                {
                    //get the index of the selected row
                    int selectedRowIndex = this.dataGridView1.SelectedCells[i].RowIndex;
                    //get the selected row
                    DataGridViewRow selectedRow = dataGridView1.Rows[selectedRowIndex];
                    //get the selected quantity, price and total
                    double selectedQuantity = Convert.ToInt32(selectedRow.Cells[1].Value);
                    double selectedPrice = Convert.ToDouble(selectedRow.Cells[2].Value);
                    double selectedTotal = Convert.ToDouble(selectedRow.Cells[3].Value);
                    //set the new quantity and total. limit the minimum quantity to 1
                    if (selectedQuantity > 1)
                    {
                        selectedRow.Cells[1].Value = --selectedQuantity;
                    }

                    selectedRow.Cells[3].Value = selectedPrice * selectedQuantity;
                    //subtract the old total from the totalAmount
                    totalAmount -= selectedTotal;
                    //add the new total to the total amount
                    totalAmount += selectedPrice * selectedQuantity;
                }
                this.labelTotal.Text = totalAmount.ToString();
            }
            else
            {
                MessageBox.Show("You cannot decrease an inexisting quantity!");
            }
        }

        private void cbShops2_SelectedIndexChanged(object sender, EventArgs e)
        {
            string selectedShopName = this.cbShops2.SelectedItem.ToString();
            if (selectedShopName != "Select a shop")
            {
                selectedShopId = getShopId(selectedShopName);
                if (selectedShopId != 0)
                {
                    this.cbItems2.Items.Clear();
                    List<Item> items = getShopItems(selectedShopId);   //get all the items
                    foreach (Item item in items) //go through the list of items and add their names to the combo box
                    {
                        this.cbItems2.Items.Add(item.Name);
                    }
                    this.cbItems2.SelectedIndex = 0;
                }
            }
        }

        private void cbItems2_SelectedIndexChanged(object sender, EventArgs e)
        {
            string selectedShopName = this.cbShops2.SelectedItem.ToString();
            string selectedItemName = this.cbItems2.SelectedItem.ToString();
            Item selectedItem = getItem(selectedShopId, selectedItemName);
            this.txtQuantityStock.Text = db.getItemQuantity(selectedItem.Id).ToString();
        }

        private void btnOrder_Click(object sender, EventArgs e)
        {
            if (this.txtQuantityOrder.Text == "")
            {
                MessageBox.Show("Enter a quantity");
            }
            else
            {
                int quantity = Convert.ToInt32(this.txtQuantityOrder.Text);
                if (quantity > 0)
                {
                    string selectedShopName = this.cbShops2.SelectedItem.ToString();
                    string selectedItemName = this.cbItems2.SelectedItem.ToString();
                    Item selectedItem = getItem(selectedShopId, selectedItemName);
                    db.updateItemQuantity(selectedItem.Id, quantity);
                    MessageBox.Show("The order was successful");
                    this.txtQuantityStock.Text = db.getItemQuantity(selectedItem.Id).ToString();
                }
                else
                {
                    MessageBox.Show("Enter a valid quantity");
                }
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (this.txtUserId.Text == "")
            {
                MessageBox.Show("Enter the user's Id");
            }
            else
            {
                int user_Id = Convert.ToInt32(this.txtUserId.Text);
                if (user_Id > 0)
                {
                    double balance = db.getUserBalance(user_Id);
                    this.txtBalance.Text = balance.ToString();
                }
                else
                {
                    MessageBox.Show("Enter a valid user Id");
                }
            }
        }

        private int getUserId()
        {
            if (this.txtUserId.Text == "")
            {
                MessageBox.Show("Enter the user's Id");
            }
            else
            {
                int user_Id = Convert.ToInt32(this.txtUserId.Text);
                if (user_Id > 0)
                {
                    return user_Id;
                }
                else
                {
                    MessageBox.Show("Enter a valid user Id");
                }
            }
            return 0;
        }
    }
}
